package hook

import (
	"api/public/nsq"
	"bytes"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
)

func init() {
	server.AddFinisher("Logger", func(operation *server.Operation) {
		//添加一些日志性质的数据在这里
		//data:=operation.Output.Writer.Bytes()
		//operation.Logout(string(data))

		if nsq.Producer != nil {
			var content []byte
			var bf = bytes.NewBuffer(content)
			//ChanKey:
			bf.WriteString(fmt.Sprintf("%s\n", operation.ChainKey))
			//HOST:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Host))
			//Method:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Method))
			//URL:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.URL))
			//RequestURI:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.RequestURI))
			//Referer:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Referer()))
			//RemoteAddr:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.RemoteAddr))
			//User-Agent:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Header.Get("User-Agent")))
			//X-AUTH-TOKEN:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Header.Get("X-AUTH-TOKEN")))
			//Access-Token:
			bf.WriteString(fmt.Sprintf("%s\n", operation.Input.Request.Header.Get("a-auth-token")))
			//Request:
			bf.WriteString(fmt.Sprintf("%v\n", string(operation.Input.Json)))
			//Response:
			bf.WriteString(fmt.Sprintf("%v\n", operation.Output.Writer.String()))

			//创建文件
			url := operation.Input.Request.URL.String()
			url = ez.ReplaceAll(url, `[^a-zA-z0-9]`, "-")
			filePath := fmt.Sprintf(
				"./var/logs/request/%s_%s_%s_.log",
				ez.GetDateYMDHIS("", "", ""),
				url,
				operation.ChainKey,
			)
			ez.CreateFile(filePath, bf.Bytes())
			e := nsq.Producer.Publish("GateWayLog", []byte(filePath))
			ez.PrintError(e)
		}

	})
}
